package cn.iocoder.yudao.module.engine.audio;

import java.io.*;

// ffmpeg -i "C:\Users\admin\Desktop\audio\mp3\beijing_5.mp3" -c:a aac -b:a 128k "C://Users/admin/Desktop/audio/aac/beijing_5.aac"
public class AudioConversionService {

    public static void convertMp3ToAac(String sourcePath, String targetPath) {
        try {
            // 构建FFmpeg命令，注意加上引号以处理路径中的空格
            String command = String.format("ffmpeg -i \"%s\" -c:a aac -b:a 128k \"%s\"", sourcePath, targetPath);
            System.out.println(command);

            // 执行命令
            Process process = Runtime.getRuntime().exec(command);

            // 创建输入流和错误流的读取器
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));

            // 输出FFmpeg的标准输出
            String line;
            while ((line = stdInput.readLine()) != null) {
                System.out.println(line);
            }

            // 输出FFmpeg的错误输出
            while ((line = stdError.readLine()) != null) {
                System.err.println(line);
            }

            // 等待进程完成
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                System.out.println("转换完成！");
            } else {
                System.out.println("转换失败，错误代码：" + exitCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("转换失败！");
        }
    }

    public static void main(String[] args) {
        String dir = "C://Users/admin/Desktop/audio/mp3";
        File[] files = new File(dir).listFiles();
        if (files != null) {
            for (File mp3File : files) {
                if (mp3File.isFile() && mp3File.getName().endsWith(".mp3")) {
                    String targetPath = String.format("C://Users/admin/Desktop/audio/aac/%s.aac", mp3File.getName().replace(".mp3", ""));
                    convertMp3ToAac(mp3File.getAbsolutePath(), targetPath);
                }
            }
        }
    }
}
